Creating React Components in React JS
Creating React Components is one of the most important concepts in React JS. Components allow developers to divide a user interface (UI) into small, reusable, and manageable parts. Instead of writing an entire website in one large file, developers can create separate components for headers, navigation bars, buttons, forms, cards, and other UI elements.
Course Link: JustAcademy React JS Training Course
Demo Link: Register for React JS Course Demo
1. What Is a React Component?
A React component is an independent, reusable piece of a user interface. It is usually written as a JavaScript function that returns JSX, which describes what should appear on the screen.
For example, a website may contain a Header component, Navbar component, ProductCard component, Footer component, and App component. These components can be combined to build a complete application.
Example
function Welcome() {
return <h1>Welcome to React JS!</h1>;
}
export default Welcome;
Explanation:
function Welcome() defines a component named Welcome.
return specifies the UI that the component displays.
is JSX markup representing a heading.
export default Welcome allows the component to be imported into another file.
2. Why Do We Create React Components?
- Reusability: Write a component once and use it in multiple places.
- Maintainability: Update a specific part of the UI without rewriting the entire application.
- Readability: Divide complex interfaces into smaller, understandable pieces.
- Separation of concerns: Keep related UI markup and logic together.
- Consistency: Reuse the same design and behavior across different pages.
- Scalability: Organize applications as they grow in size and complexity.
- Testing: Smaller components are often easier to test independently.
3. Types of React Components
React supports function components and class components. Function components are the recommended approach for most new React code.
3.1 Function Components
A function component is a JavaScript function that returns JSX. It can receive props and use Hooks such as useState and useEffect when needed.
function Greeting() {
return <h2>Hello, Student!</h2>;
}
export default Greeting;
3.2 Arrow Function Components
Arrow functions provide another way to define function components.
const Greeting = () => {
return <h2>Hello, Student!</h2>;
};
export default Greeting;
The following shorter syntax is also valid:
const Greeting = () => <h2>Hello, Student!</h2>;
export default Greeting;
3.3 Class Components
Class components extend React's Component class and define a render() method. They are still supported, but function components are generally preferred for new code.
import { Component } from 'react';
class Greeting extends Component {
render() {
return <h2>Hello, Student!</h2>;
}
}
export default Greeting;
Comparison Table
| Feature |
Function Component |
Class Component |
| Definition |
JavaScript function |
JavaScript class extending Component |
| UI output |
Returns JSX |
Returns JSX from render() |
| State |
Uses Hooks such as useState |
Uses this.state and this.setState |
| Lifecycle behavior |
Uses Hooks such as useEffect where appropriate |
Uses lifecycle methods |
| Recommended for new code |
Yes |
Generally no |
4. Rules for Creating React Components
- Use a capital letter: Component names should begin with an uppercase letter, such as
Header or ProductCard.
- Return valid JSX: A component should return valid React-renderable content.
- Use one root element when needed: Wrap multiple sibling elements in a parent element or a React Fragment.
- Keep components at the top level: Avoid defining component functions inside other components.
- Use props for input data: Pass data from a parent component to a child component through props.
- Keep rendering pure: Avoid changing external variables or performing side effects during rendering.
- Export when necessary: Export components that need to be used in other modules.
Correct Example
function Profile() {
return (
<div>
<h2>User Profile</h2>
<p>Welcome to your profile.</p>
</div>
);
}
export default Profile;
Using a Fragment
A React Fragment groups multiple JSX elements without adding an extra DOM element.
function AppTitle() {
return (
<>
<h1>React JS</h1>
<p>Learn to build user interfaces.</p>
</>
);
}
5. Creating Your First React Component
Follow these steps to create and use a simple React component.
Step 1: Create a Component File
Create a file named Welcome.jsx inside your project's source directory.
Step 2: Define the Component
function Welcome() {
return (
<div>
<h1>Welcome to My Website</h1>
<p>This is my first React component.</p>
</div>
);
}
export default Welcome;
Step 3: Import the Component
Import the component into your App.jsx file.
import Welcome from './Welcome.jsx';
function App() {
return (
<main>
<Welcome />
</main>
);
}
export default App;
Step 4: Render the App
In a typical React application, the entry file mounts the root component into the HTML page.
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.jsx';
createRoot(document.getElementById('root')).render(
<StrictMode>
<App />
</StrictMode>
);
Result: The browser displays the heading “Welcome to My Website” and the paragraph “This is my first React component.”
Note: The entry-file setup may differ depending on your React project template or framework.
6. Creating Reusable Components
A reusable component can be used multiple times in an application. For example, a Button component can display different labels while maintaining the same basic structure.
Example: Reusable Button
function Button() {
return <button>Click Me</button>;
}
function App() {
return (
<div>
<Button />
<Button />
<Button />
</div>
);
}
export default App;
Here, the same Button component is rendered three times. This avoids repeating the button's markup.
7. Passing Data Through Props
Props, short for properties, allow a parent component to pass information to a child component. Props are read-only inputs and should not be modified by the receiving component.
Example
function Greeting(props) {
return <h2>Hello, {props.name}!</h2>;
}
function App() {
return (
<div>
<Greeting name="Aarav" />
<Greeting name="Priya" />
<Greeting name="Rahul" />
</div>
);
}
export default App;
Output: Three greetings appear, each using the name passed to the component.
Destructuring Props
You can extract props directly from the function parameter to make the code cleaner.
function Greeting({ name, city }) {
return (
<p>{name} lives in {city}.</p>
);
}
function App() {
return <Greeting name="Priya" city="Mumbai" />;
}
Default Values for Props
function Greeting({ name = 'Guest' }) {
return <h2>Hello, {name}!</h2>;
}
If the caller does not provide a name prop, the component uses “Guest”. The default applies when the value is undefined, not when it is explicitly null.
8. Parent and Child Components
React applications commonly use a component hierarchy. A parent component renders one or more child components, helping organize the UI into logical sections.
Example
function Header() {
return <header><h1>My Website</h1></header>;
}
function Content() {
return <section><p>Welcome to the website.</p></section>;
}
function Footer() {
return <footer><p>Copyright 2026</p></footer>;
}
function App() {
return (
<div>
<Header />
<Content />
<Footer />
</div>
);
}
export default App;
In this example, App is the parent component, while Header, Content, and Footer are child components.
9. Using the children Prop
The special children prop allows a component to display content placed between its opening and closing tags. This is useful for layouts, cards, panels, and reusable containers.
function Card({ children }) {
return (
<div className="card">
{children}
</div>
);
}
function App() {
return (
<Card>
<h2>React Learning</h2>
<p>Practice creating reusable components.</p>
</Card>
);
}
export default App;
The Card component provides a reusable wrapper, while the parent decides which content to place inside it.
10. Adding CSS to Components
You can style React components using regular CSS files and the className attribute.
Component File: Welcome.jsx
import './Welcome.css';
function Welcome() {
return (
<div className="welcome-card">
<h2>Welcome to React</h2>
<p>Build reusable user interfaces.</p>
</div>
);
}
export default Welcome;
CSS File: Welcome.css
.welcome-card {
padding: 20px;
margin: 16px;
border: 1px solid #cccccc;
border-radius: 8px;
background-color: #f5f5f5;
}
.welcome-card h2 {
color: #2563eb;
}
Important: React uses className in JSX instead of the HTML class attribute.
11. Rendering Lists of Components
When displaying multiple items, use JavaScript methods such as map() to render a component for each item. Give each sibling a stable, unique key.
function StudentCard({ name }) {
return <li>{name}</li>;
}
function App() {
const students = [
{ id: 1, name: 'Aarav' },
{ id: 2, name: 'Priya' },
{ id: 3, name: 'Rahul' }
];
return (
<ul>
{students.map((student) => (
<StudentCard key={student.id} name={student.name} />
))}
</ul>
);
}
export default App;
The key helps React identify items between renders. It is not automatically passed to the component as a regular prop. If the child needs the ID, pass it separately, for example id={student.id}.
12. Adding State to a Component
State stores information that can change over time. When state changes through a state setter, React can render the component again to display the updated value.
Example: Counter Component
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>
Increase
</button>
</div>
);
}
export default Counter;
Explanation:
useState(0) initializes the count to zero.
count stores the current state value.
setCount updates the state.
onClick handles the button click.
- React renders the updated count after the state changes.
Hooks such as useState must be called at the top level of a function component or custom Hook, not inside loops, conditions, or nested functions.
13. Conditional Rendering in Components
Conditional rendering allows a component to display different content depending on a condition.
Example
function LoginMessage({ isLoggedIn }) {
if (isLoggedIn) {
return <h2>Welcome Back!</h2>;
}
return <h2>Please Log In</h2>;
}
function App() {
return (
<div>
<LoginMessage isLoggedIn={true} />
<LoginMessage isLoggedIn={false} />
</div>
);
}
The component displays a different message depending on the value of isLoggedIn.
14. Organizing Components into Separate Files
For a larger application, create separate files for components that have distinct responsibilities. This makes code easier to find, maintain, and reuse.
Suggested Folder Structure
src/
components/
Header.jsx
Footer.jsx
Button.jsx
StudentCard.jsx
App.jsx
main.jsx
index.css
Named Export Example
In Header.jsx:
export function Header() {
return <header><h1>My Application</h1></header>;
}
In App.jsx:
import { Header } from './components/Header.jsx';
function App() {
return (
<div>
<Header />
</div>
);
}
export default App;
Note: A default export is imported without braces, while a named export is imported using braces. The import path and exported name must match the module.
15. Complete Practical Example: Student Management UI
This example combines reusable components, props, list rendering, and CSS classes to create a simple student list.
function StudentCard({ name, course }) {
return (
<article className="student-card">
<h2>{name}</h2>
<p>Course: {course}</p>
</article>
);
}
function StudentList() {
const students = [
{ id: 1, name: 'Aarav', course: 'React JS' },
{ id: 2, name: 'Priya', course: 'JavaScript' },
{ id: 3, name: 'Rahul', course: 'Web Development' }
];
return (
<section>
<h1>Student List</h1>
{students.map((student) => (
<StudentCard
key={student.id}
name={student.name}
course={student.course}
/>
))}
</section>
);
}
export default function App() {
return (
<main>
<StudentList />
</main>
);
}
How It Works
App is the main component.
StudentList stores the sample student data and renders the list.
map() creates one StudentCard for each student.
StudentCard receives the student's name and course through props.
- The
key uniquely identifies each list item among its siblings.
16. Common Mistakes When Creating Components
| Mistake |
Why It Is a Problem |
Correct Approach |
| Using a lowercase component name |
React interprets lowercase JSX tags as built-in HTML elements. |
Use names such as Header or Profile. |
| Forgetting to return JSX |
The component may render nothing. |
Return the intended JSX. |
| Returning multiple adjacent elements without a wrapper |
JSX requires a single returned element or Fragment. |
Use a parent element or Fragment. |
| Calling a component as a regular function |
It bypasses React's normal component rendering behavior. |
Render it with JSX, such as . |
| Defining a component inside another component |
It can create a new component type on each render and cause state or performance problems. |
Define components at the module's top level. |
| Modifying props directly |
Props are read-only inputs. |
Pass new values from the parent or use state for local changing data. |
| Using array indexes as keys in changing lists |
Items may be incorrectly matched when order changes. |
Prefer stable IDs from the data. |
| Calling Hooks conditionally |
It violates the Rules of Hooks. |
Call Hooks at the top level of the component. |
| Mixing too many responsibilities into one component |
The component becomes difficult to maintain and test. |
Split it into logical, reusable components where helpful. |
17. Best Practices for Creating React Components
- Use descriptive names such as
ProductCard, SearchBar, and Navbar.
- Prefer function components for new React code.
- Keep each component focused on a clear responsibility.
- Reuse components instead of duplicating the same UI markup.
- Use props to configure reusable components.
- Use state only for information that needs to change over time.
- Keep components pure: rendering should not mutate external data or perform side effects.
- Use stable keys when rendering arrays of components.
- Keep component files organized and use consistent import/export conventions.
- Choose component boundaries based on clarity and reuse rather than splitting every single HTML tag into a component.
- Use accessible HTML elements, meaningful labels, and appropriate button types.
- Test important component behavior and edge cases.
18. Component Creation Workflow
- Identify a UI section that can be represented as a component.
- Choose a clear, capitalized component name.
- Create a function that returns the required JSX.
- Accept props if the component needs data from its parent.
- Add state or event handlers only when needed.
- Export the component if another file needs to use it.
- Import and render the component inside its parent.
- Add styling and test the component in the application.
19. Interview Questions and Answers
Q1. What is a React component?
A React component is a reusable UI building block that describes part of an application's interface.
Q2. How do you create a function component?
Define a JavaScript function with a capitalized name and return JSX from it.
Q3. Why should component names start with a capital letter?
Capitalization allows React to distinguish custom components from built-in HTML elements in JSX.
Q4. What is the difference between props and state?
Props are inputs passed to a component, usually by its parent. State is component-managed data that can change and trigger a re-render.
Q5. Can a component be reused?
Yes. A component can be rendered in multiple places and configured with different props.
Q6. What is JSX?
JSX is a JavaScript syntax extension that lets developers describe UI using markup-like syntax inside JavaScript code.
Q7. What is the purpose of export and import?
Export makes a component available from a module, while import lets another module use it.
Q8. What is a parent component?
A parent component is a component that renders or contains other components.
Q9. What is the children prop?
The children prop represents content nested between a component's opening and closing tags.
Q10. Why are keys used when rendering lists?
Keys help React identify list items between renders so it can update the UI correctly.
Q11. Should you define one component inside another component?
Generally, no. Define component functions at the top level to avoid creating a new component type on each render.
Q12. Which type of component is recommended for new React projects?
Function components are generally recommended. They support Hooks and are the standard approach in modern React development.
20. Revision Checklist
- Understand the meaning and purpose of React components.
- Know how to create function and arrow function components.
- Understand JSX and component naming rules.
- Know how to import and export components.
- Understand reusable components and component composition.
- Know how to pass props and use default prop values.
- Understand parent-child relationships and the children prop.
- Know how to apply CSS to components.
- Understand list rendering and stable keys.
- Know the basics of state and event handling.
- Recognize common component creation mistakes.
21. Official React Documentation
Conclusion
Creating React Components helps developers build user interfaces that are reusable, organized, maintainable, and scalable. By understanding function components, JSX, props, state, component composition, and list rendering, beginners can start building real React applications with confidence.
To learn more, visit the JustAcademy React JS Training Course or register for a React JS course demo.